<template>
  <div class="set">
    <div class="set-title padd-20">团购设置</div>

    <div class="set-logistics padd-20" @click="handleRouteJump('logistics')">
      <span class="left">物流方式</span>

      <div class="right">
        <span :class="{ 'text-has': hasLogistics }">{{ logisticsCpt }}</span>
        <img src="@/assets/addstart/introduce/introduce_arrow.png" />
      </div>
    </div>

    <div class="set-date padd-20">
      <span class="left">团购时间</span>

      <div class="right">
        <div class="date-box">
          <div class="starttime" @click="openDatePicker('start')">
            <span>开始</span>
            <span>{{
              dateShow.startDate ? dateShow.startDate : "请选择开始日期"
            }}</span>
          </div>

          <div class="endtime" @click="openDatePicker('end')">
            <span>结束</span>
            <span>{{
              dateShow.endDate ? dateShow.endDate : "请选择结束日期"
            }}</span>
          </div>
        </div>

        <img src="@/assets/addstart/introduce/introduce_arrow.png" />
      </div>
    </div>

    <div class="set-drawback padd-20">
      <div class="left-box">
        <span class="left">允许退款</span>
        <span class="tip">关闭后不允许退款</span>
      </div>

      <div class="right">
        <nut-switch class="switch" v-model="checked" active-color="#40AE36" />
      </div>
    </div>

    <!-- 日期选择器 -->
    <nut-datepicker
      v-model:visible="isShowStartPicker"
      v-model="dateVal.startDate"
      type="datetime"
      :formatter="formatter"
      :is-show-chinese="true"
      @confirm="handleStartDate"
    ></nut-datepicker>
    <nut-datepicker
      v-model:visible="isShowEndPicker"
      v-model="dateVal.endDate"
      type="datetime"
      :formatter="formatter"
      :is-show-chinese="true"
      @confirm="handleEndDate"
    ></nut-datepicker>
  </div>
</template>

<script lang="ts" setup>
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, onActivated, computed, watch } from "vue";

// - router
const router = useRouter();
const route = useRoute();

// - data
const isShowStartPicker = ref(false);
const isShowEndPicker = ref(false);
const checked = ref(false); // 是否退款
const logistics = ref<any>(); // 物流内容
const hasLogistics = ref(false);

const dateVal = reactive({
  startDate: new Date(), // 开始时间
  endDate: new Date(), // 结束时间
});
const dateShow = ref({
  startDate: "", // 开始时间(格式化后)
  endDate: "", // 结束时间(格式化后)
});

// - computed
const logisticsCpt = computed(() => {
  hasLogistics.value = false;
  let showText = "设置物流内容";

  if (logistics.value) {
    if (logistics.value.village && logistics.value.delivery) {
      showText = "小区自提/快递";
      hasLogistics.value = true;
    } else if (logistics.value.village) {
      showText = "小区自提";
      hasLogistics.value = true;
    } else if (logistics.value.delivery) {
      showText = "快递";
      hasLogistics.value = true;
    }
  }

  return showText;
});

// - watch
// 解决遮罩层出现后，页面也会滚动的问题
watch(isShowStartPicker, (newVal) => {
  if (newVal) {
    document.body.style.overflow = "hidden";
    // document.body.style.position = 'fixed'
  } else {
    document.body.style.overflow = "";
    // document.body.style.position = 'static'
  }
});
watch(isShowEndPicker, (newVal) => {
  if (newVal) {
    document.body.style.overflow = "hidden";
    // document.body.style.position = 'fixed'
  } else {
    document.body.style.overflow = "";
    // document.body.style.position = 'static'
  }
});

// - methods
const formatter = (type: string, option: any) => {
  switch (type) {
    case "year":
      option.text += "年";
      break;
    case "month":
      option.text += "月";
      break;
    case "day":
      option.text += "日";
      break;
    case "hour":
      option.text += "时";
      break;
    case "minute":
      option.text += "分";
      break;
    default:
      option.text += "";
  }
  return option;
};
const openDatePicker = (which: "start" | "end") => {
  which == "start"
    ? (isShowStartPicker.value = true)
    : (isShowEndPicker.value = true);
};
const handleStartDate = ({ selectedValue, selectedOptions }: any) => {
  let date = selectedValue.slice(0, 3).join("-");
  let time = selectedValue.slice(3).join(":");
  dateShow.value.startDate = date + " " + time;
};
const handleEndDate = ({ selectedValue, selectedOptions }: any) => {
  let date = selectedValue.slice(0, 3).join("-");
  let time = selectedValue.slice(3).join(":");
  dateShow.value.endDate = date + " " + time;
};
const stopScroll = () => {
  var mo = function (e: any) {
    e.preventDefault();
  };
  document.body.style.overflow = "hidden";
  document.addEventListener("touchmove", mo, false); // 禁止页面滑动
};
const canScroll = () => {
  var mo = function (e: any) {
    e.preventDefault();
  };
  document.body.style.overflow = ""; // 出现滚动条
  document.removeEventListener("touchmove", mo, false);
};
const handleCommit = () => {
  const payload = {
    logistics: logistics.value,
    isChecked: checked.value,
    startDate: dateShow.value.startDate,
    endDate: dateShow.value.endDate,
  };

  return payload;
};
const handleRouteJump = (path: string) => {
  if (route.path.includes("community")) {
    router.push({
      path,
      query: {
        isCommunity: 1,
      },
    });
  } else {
    router.push(path);
  }
};

// - lifecycle
function init() {
  // const localDateShow = window.localStorage.getItem('dateShow')
  // localDateShow && (dateShow.value = JSON.parse(localDateShow))
  // const localLogistics = window.localStorage.getItem('logistics')
  // localLogistics && (logistics.value = JSON.parse(localLogistics))
  // const localChecked = window.localStorage.getItem('checked')
  // localChecked && (checked.value = JSON.parse(localChecked))
}
init();
// onBeforeUnmount(() => {
//   window.localStorage.setItem('dateShow', JSON.stringify(dateShow.value))
//   window.localStorage.setItem('logistics', JSON.stringify(logistics.value))
//   window.localStorage.setItem('checked', JSON.stringify(checked.value))
// })

onActivated(() => {
  let localLogisticsSelectedArr = window.localStorage.getItem(
    "setinfo-logistics-selectedArr"
  );

  // 读取本地缓存的团购设置中的物流方式数据
  if (route.path.includes("community")) {
    localLogisticsSelectedArr = window.localStorage.getItem(
      "setinfo-logistics-selectedArr-community"
    );
  }
  if (localLogisticsSelectedArr) {
    const logisticsSelectedArr = JSON.parse(localLogisticsSelectedArr);
    logistics.value = logisticsSelectedArr;
  }
});

// - expose
const resetData = () => {
  dateShow.value = {
    startDate: "",
    endDate: "",
  };
  checked.value = false;
  logistics.value = "";
  hasLogistics.value = false;

  window.localStorage.removeItem("setinfo-logistics-selectedArr");
  window.localStorage.removeItem("setinfo-logistics-selectedArr-community");
  window.localStorage.removeItem("logisticIdArr");
  window.localStorage.removeItem("deliveryFlag");
};
defineExpose({ handleCommit, resetData });
</script>

<style lang="scss" scoped>
.set {
  background-color: #ffffff;
  margin-top: 20px;
  border-radius: 20px;
  overflow: hidden;

  .padd-20 {
    padding: 0 20px;
  }
  .text-has {
    font-size: 28px;
    font-family: PingFang-SC-Regular, PingFang-SC;
    font-weight: 400;
    color: #000000;
  }

  .left {
    font-size: 28px;
    font-family: PingFang-SC-Regular, PingFang-SC;
    font-weight: 400;
    color: #000000;
  }
  .right {
    display: flex;
    align-items: center;
    font-size: 28px;
    font-family: PingFang-SC-Regular, PingFang-SC;
    font-weight: 400;
    color: #999999;
    overflow: hidden;
  }

  .set-title {
    display: flex;
    align-items: center;
    height: 90px;
    box-shadow: inset 0px -1px 0px 0px #eeeeee;
    font-size: 32px;
    font-family: PingFang-SC-Medium, PingFang-SC;
    font-weight: 500;
    color: #000000;
  }

  .set-logistics {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 96px;
    box-shadow: inset 0px -1px 0px 0px #eeeeee;

    .right {
      img {
        display: block;
        width: 26px;
        margin-right: 20px;
      }
    }
  }

  .set-date {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 130px;
    box-shadow: inset 0px -1px 0px 0px #eeeeee;

    .right {
      display: flex;
      align-items: center;
      overflow: hidden;

      .date-box {
        display: flex;
        flex-direction: column;
        justify-content: center;
        overflow: hidden;

        .starttime,
        .endtime {
          display: flex;
          text-align: right;
          white-space: nowrap;

          span:last-of-type {
            display: block;
            color: #40ae36;
            min-width: 245px;
            margin-left: 25px;
          }
        }
        .endtime {
          margin-top: 16px;
        }
      }

      img {
        display: block;
        width: 26px;
        margin: 0 20px 0 11px;
      }
    }
  }

  .set-drawback {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 120px;
    overflow: hidden;

    .left-box {
      display: flex;
      flex-direction: column;

      .tip {
        font-size: 24px;
        font-family: PingFang-SC-Regular, PingFang-SC;
        font-weight: 400;
        color: #999999;
        margin-top: 8px;
      }
    }

    .right {
      margin-right: 20px;

      // .switch {
      //   width: 90px;
      //   height: 54px;

      //   :deep(.switch-button) {
      //     width: 45px;
      //     height: 45px;
      //   }
      // }
    }
  }
}
</style>
